package com.shou.domain.user.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shou.domain.common.AbstractService;
import com.shou.domain.common.PageQueryEntity;
import com.shou.domain.user.model.entity.UserEntity;
import com.shou.domain.user.repository.IUserRepository;
import com.shou.domain.user.service.IUserService;
import com.shou.types.common.Constants;
import com.shou.types.common.ReturnCodeEnum;
import com.shou.types.common.RoleEnum;
import com.shou.types.common.TableNameEnum;
import com.shou.types.exception.DataNotFoundException;
import com.shou.types.exception.InvalidParameterException;
import com.shou.types.utils.RSAUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserService extends AbstractService implements IUserService {

    @Resource
    private IUserRepository userRepository;

    @Override
    public void insertUser(UserEntity userEntity) {
        validateUserEntity(userEntity);
        if(StringUtils.isEmpty(userEntity.getPassword())) {
            userEntity.setPassword(RSAUtil.encryptByPublicKey(Constants.DEFAULT_PASSWORD));
        }
        userRepository.insert(userEntity);
    }

    @Override
    public UserEntity getUserById(Integer id) {
        return userRepository.getUserById(id);
    }

    @Override
    public IPage<UserEntity> pageQuery(PageQueryEntity pageQueryEntity) {
        pageQueryEntity.setSortName(camelToSnake(pageQueryEntity.getSortName()));
        validateQueryParams(pageQueryEntity, TableNameEnum.USER);
        IPage<UserEntity> pageResult = userRepository.getUsersPage(pageQueryEntity);
        // 对分页查询结果进行解密
        if (pageResult != null && pageResult.getRecords() != null) {
            for (UserEntity entity : pageResult.getRecords()) {
                super.handleDecryption(entity);
            }
        }
        return pageResult;
    }

    @Override
    public void updateUserById(UserEntity userEntity) {
        Integer id = userEntity.getId();
        if(id == null || !checkIfExistById(id, TableNameEnum.USER)){
            throw new DataNotFoundException(DataNotFoundException.ErrorCodeEnum.USER_INFO_NOT_FOUND, "id: " + id, ReturnCodeEnum.RC406);
        }
        validateUserEntity(userEntity, userEntity.getId());
        userRepository.updateUserById(userEntity);
    }

    @Override
    public UserEntity authenticate(String userName, String password) {
        UserEntity userEntity = userRepository.getUserByName(userName);
        if(userEntity == null)
            throw new DataNotFoundException(DataNotFoundException.ErrorCodeEnum.USER_NAME_NOT_FOUND, "请先注册或使用正确的用户名密码登录", ReturnCodeEnum.RC406);
        // 解密数据库中的密码
        super.handleDecryption(userEntity);
        // 明文比较，判断登录是否成功
        if(!RSAUtil.decryptByPrivateKey(password).equals(userEntity.getPassword()))
            throw new InvalidParameterException(InvalidParameterException.ErrorCodeEnum.INVALID_INPUT_PASSWORD, "请重新输入", ReturnCodeEnum.RC406);
        if(userEntity.getRole() == null || !RoleEnum.checkRole(userEntity.getRole()))
            throw new InvalidParameterException(InvalidParameterException.ErrorCodeEnum.INVALID_USER_ROLE, "请联系管理员", ReturnCodeEnum.RC401);
        return userEntity;
    }

    @Override
    public void resetPassWordById(Integer id) {
        if(id == null || !checkIfExistById(id, TableNameEnum.USER)){
            throw new DataNotFoundException(DataNotFoundException.ErrorCodeEnum.USER_INFO_NOT_FOUND, "id: " + id, ReturnCodeEnum.RC406);
        }
        userRepository.resetPassWordById(id);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        super.deleteByIds(ids, TableNameEnum.USER);
    }

    @Override
    public void deleteAll() {
        super.deleteAll(TableNameEnum.USER);
    }

    private void validateUserEntity(UserEntity user, Integer... excludeIds) {
        validateName(user.getName(), TableNameEnum.USER.getEnTableName(), excludeIds);
    }
}